<template>
  <div class="search-condition">
    <a-button type="text" class="icon-add-btn" @click="addSearchCondition">
      <template #icon>
        <icon-plus />
      </template>
      <template #default>添加过滤条件</template>
    </a-button>

    <div v-for="condition in searchConditions" :key="condition.id" class="condition-row">
      <a-select v-model="condition.field" placeholder="请选择字段">
        <a-option v-for="field in props.fieldsConfig" :key="field.field" :value="field.field">{{ field.label
        }}</a-option>
      </a-select>
      <a-select v-model="condition.operator" placeholder="请选择操作符">
        <a-option v-for="operator in getOperators(condition.field)" :key="operator.value" :value="operator.value">
          {{ operator.label }}
        </a-option>
      </a-select>
      <component :is="matchRender(condition.field)" v-model="condition.value"
        v-bind="getComponentProps(condition.field)" :placeholder="getPlaceholder(condition.field)"
        :allow-clear="true" />
      <a-button type="text" class="icon-btn" @click="removeSearchCondition(condition.id)">
        <template #icon>
          <icon-delete />
        </template>
      </a-button>
    </div>
    <div class="search-condition-footer">
      <a-button type="primary" @click="handleSearch">搜索</a-button>
      <a-button @click="handleReset" class="icon-clear-btn">
        <template #icon>
          <icon-refresh />
        </template>
        <template #default>重置</template>
      </a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { SearchOperator, type SearchCondition, SearchOperatorOptions } from '../../models/SearchModels';
import { ref, type PropType, watch } from 'vue';
import { SearchFieldType, type SearchFieldConfig } from '../../models/BaseModels';
import { DatePicker, Input, InputNumber, Select } from '@arco-design/web-vue';
import { inject } from 'vue';

const callHandleSearch = inject<() => Promise<void>>('handleSearch');

const props = defineProps({
  fieldsConfig: {
    type: Array as PropType<SearchFieldConfig[]>,
    required: true
  },

  toolsBarSearchForm: {
    type: Array as PropType<SearchCondition[]>,
    required: true
  }
})

const emit = defineEmits(['update:toolsBarSearchForm']);

watch(() => props.toolsBarSearchForm, (newValue) => {
  emit('update:toolsBarSearchForm', newValue);
});

const searchConditions = ref<SearchCondition[]>([...props.toolsBarSearchForm]);

// 字段类型对应的操作符
const operatorMap: Record<SearchFieldType, SearchOperator[]> = {
  [SearchFieldType.input]: [SearchOperator.EQUAL, SearchOperator.LIKE],
  [SearchFieldType.inputNumber]: [SearchOperator.EQUAL, SearchOperator.GREATER_THAN, SearchOperator.LESS_THAN, SearchOperator.GREATER_THAN_OR_EQUAL, SearchOperator.LESS_THAN_OR_EQUAL],
  [SearchFieldType.numberRange]: [SearchOperator.EQUAL, SearchOperator.GREATER_THAN_OR_EQUAL, SearchOperator.LESS_THAN_OR_EQUAL, SearchOperator.GREATER_THAN, SearchOperator.LESS_THAN],
  [SearchFieldType.select]: [SearchOperator.EQUAL],
  [SearchFieldType.multiSelect]: [SearchOperator.IN],
  [SearchFieldType.date]: [SearchOperator.EQUAL, SearchOperator.GREATER_THAN, SearchOperator.LESS_THAN, SearchOperator.GREATER_THAN_OR_EQUAL, SearchOperator.LESS_THAN_OR_EQUAL],
  [SearchFieldType.dateTimeRange]: [SearchOperator.EQUAL, SearchOperator.GREATER_THAN, SearchOperator.LESS_THAN, SearchOperator.GREATER_THAN_OR_EQUAL, SearchOperator.LESS_THAN_OR_EQUAL]
};

// 计算当前条件的可用操作符
const getOperators = (field: string) => {
  const fieldType = props.fieldsConfig.find(f => f.field === field)?.type;
  if (!fieldType) return [];

  const allowedOperators = operatorMap[fieldType] || [];

  // 过滤出符合条件的操作符，并返回 label 和 value
  return SearchOperatorOptions.filter(op => allowedOperators.includes(op.value));
};

// 获取placeholder
const getPlaceholder = (field: string) => {
  const fieldType = props.fieldsConfig.find(f => f.field === field)?.type;
  if (!fieldType) return '';
  switch (fieldType) {
    case SearchFieldType.input: return '请输入值';
    case SearchFieldType.inputNumber: return '请输入值';
    case SearchFieldType.select: return '请选择值';
    case SearchFieldType.multiSelect: return '请选择值';
    case SearchFieldType.date: return '请选择日期';
  }
}

// 获取组件的props
const getComponentProps = (field: string) => {
  const fieldConfig = props.fieldsConfig.find(f => f.field === field)
  if (!fieldConfig) return {};

  switch (fieldConfig.type) {
    case SearchFieldType.select:
      return {
        options: fieldConfig.optionsConfig?.options,
      }
    case SearchFieldType.multiSelect: return {
      options: fieldConfig.optionsConfig?.options,
      multiple: true,
      maxTagCount: 1
    }
    default: return {}
  }
}

// **匹配组件**
const matchRender = (field: string) => {
  const fieldType = props.fieldsConfig.find(f => f.field === field)?.type;
  switch (fieldType) {
    case SearchFieldType.input: return Input
    case SearchFieldType.inputNumber: return InputNumber
    case SearchFieldType.select: return Select
    case SearchFieldType.multiSelect: return Select
    case SearchFieldType.date: return DatePicker
    case SearchFieldType.dateTimeRange: return DatePicker
    case SearchFieldType.numberRange: return InputNumber
    default: return Input
  }
}


const addSearchCondition = () => {
  searchConditions.value.push({
    id: new Date().getTime().toString(),
    field: '',
    operator: null,
    value: null,
  });
}

const removeSearchCondition = (id: string) => {
  searchConditions.value = searchConditions.value.filter(condition => condition.id !== id);
  emit('update:toolsBarSearchForm', searchConditions.value);
}

// 触发BaseTable的搜索功能
const handleSearch = () => {
  if (callHandleSearch) {
    callHandleSearch();
  }
}

const handleReset = () => {
  searchConditions.value = [
    {
      id: new Date().getTime().toString(),
      field: '',
      operator: null,
      value: null,
    }
  ];
}


</script>

<style scoped>
.search-condition {
  width: 550px;
}

.condition-row {
  display: flex;
  width: 100%;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.icon-btn {
  color: black !important;
  padding: 4px;
  display: flex;
  align-items: center;
  gap: 0px;
  border: none;
}

.search-condition-footer {
  display: flex;
  align-items: center;
  gap: 10px;
}

.icon-clear-btn {
  color: black !important;
  padding: 4px;
  display: flex;
  align-items: center;
  gap: 0px;
  border: none;
  outline: none;
}

.icon-clear-btn:focus,
.icon-clear-btn:active {
  outline: none !important;
  box-shadow: none !important;
  border-color: transparent !important;
}
</style>